/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package ar.com.remiseria.frame;

import ar.com.remiseria.bo.DestinoFrecuenteBO;
import ar.com.remiseria.dao.DestinoFrecuenteDAO;
import ar.com.remiseria.entities.DestinoFrecuente;
import ar.com.remiseria.entities.Domicilio;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.ListModel;

/**
 *
 * @author gdorrego
 */
public class ABMDestinosFrecuentes extends javax.swing.JFrame {

    private List<DestinoFrecuente> listaDestinos = new ArrayList<DestinoFrecuente>();
    private DestinoFrecuente destinoSeleccionado;
    private boolean isNuevo;
    private int posicionDestino;
    
    /**
     * Creates new form ABMDestinosFrecuentes
     */
    public ABMDestinosFrecuentes() {
        initComponents();
        this.destinosJList.setModel(new DefaultListModel());
        this.getDestinosFrecuentes();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        destinosJList = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        nombreDestinoTxt = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        calleTxt = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        numeroTxt = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        pisoTxt = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        departamentoTxt = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        codigoPostalTxt = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        localidadTxt = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        provinciaTxt = new javax.swing.JTextField();
        guardarBtn = new javax.swing.JButton();
        nuevoBtn = new javax.swing.JButton();
        borrarBtn = new javax.swing.JButton();
        volverBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        destinosJList.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Destinos"));
        destinosJList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                destinosJListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(destinosJList);

        jLabel1.setText("Nombre Destino Frecuente");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "Domicilio"));

        jLabel2.setText("Calle");

        jLabel3.setText("Numero");

        jLabel4.setText("Piso");

        jLabel5.setText("Departamento");

        jLabel6.setText("C.P.");

        jLabel7.setText("Localidad");

        jLabel8.setText("Provincia");

        guardarBtn.setText("Guardar");
        guardarBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guardarBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(provinciaTxt)
                        .addGap(154, 154, 154))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(15, 15, 15)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel6)))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel2)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(calleTxt)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(numeroTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel4)
                                .addGap(3, 3, 3)
                                .addComponent(pisoTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(departamentoTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(codigoPostalTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(localidadTxt))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(guardarBtn)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(calleTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(numeroTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(pisoTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(departamentoTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(codigoPostalTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(localidadTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(provinciaTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(guardarBtn)
                .addGap(26, 26, 26))
        );

        nuevoBtn.setText("Nuevo");
        nuevoBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nuevoBtnActionPerformed(evt);
            }
        });

        borrarBtn.setText("Borrar");
        borrarBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                borrarBtnActionPerformed(evt);
            }
        });

        volverBtn.setText("Volver");
        volverBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                volverBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(nuevoBtn)
                        .addGap(39, 39, 39)
                        .addComponent(borrarBtn))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(nombreDestinoTxt))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(volverBtn)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(nombreDestinoTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(2, 2, 2)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nuevoBtn)
                    .addComponent(borrarBtn)
                    .addComponent(volverBtn))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void destinosJListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_destinosJListValueChanged
        try{
            if(!destinosJList.getValueIsAdjusting()){
                this.getDestinoSeleccionado();
                this.isNuevo = false;
            }
        }catch(Exception ex){
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, ex);
        }
    }//GEN-LAST:event_destinosJListValueChanged

    private void guardarBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarBtnActionPerformed
        this.guardarDestino();
    }//GEN-LAST:event_guardarBtnActionPerformed

    private void nuevoBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoBtnActionPerformed
        this.limpiarCampos();
        this.isNuevo = true;
//        destinosJList.setEnabled(false);
        nombreDestinoTxt.requestFocus(true);
    }//GEN-LAST:event_nuevoBtnActionPerformed

    private void borrarBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_borrarBtnActionPerformed
        try{
            this.borrarSeleccionado();
        }catch(Exception ex){
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, ex);
        }
    }//GEN-LAST:event_borrarBtnActionPerformed

    private void volverBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_volverBtnActionPerformed
        MenuPrincipalFrame mpf = new MenuPrincipalFrame();
        mpf.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_volverBtnActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ABMDestinosFrecuentes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ABMDestinosFrecuentes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ABMDestinosFrecuentes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ABMDestinosFrecuentes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ABMDestinosFrecuentes().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton borrarBtn;
    private javax.swing.JTextField calleTxt;
    private javax.swing.JTextField codigoPostalTxt;
    private javax.swing.JTextField departamentoTxt;
    private javax.swing.JList destinosJList;
    private javax.swing.JButton guardarBtn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField localidadTxt;
    private javax.swing.JTextField nombreDestinoTxt;
    private javax.swing.JButton nuevoBtn;
    private javax.swing.JTextField numeroTxt;
    private javax.swing.JTextField pisoTxt;
    private javax.swing.JTextField provinciaTxt;
    private javax.swing.JButton volverBtn;
    // End of variables declaration//GEN-END:variables

    private void getDestinosFrecuentes() {
        DestinoFrecuenteBO destinoFrecuenteBO = new DestinoFrecuenteBO();
        List<DestinoFrecuente> losDestinos = new ArrayList<DestinoFrecuente>();
        
        try{
            losDestinos = destinoFrecuenteBO.getAllDestinos();
        }catch(Exception ex){
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, ex);
        }
        
        if(losDestinos != null && !losDestinos.isEmpty()){
//            ListModel modelo = destinosJList.getModel();
            DefaultListModel modelo = (DefaultListModel) destinosJList.getModel();
            for(DestinoFrecuente df : losDestinos){
                modelo.addElement(df.getNombre());
                listaDestinos.add(df);
            }
            destinosJList.setModel(modelo);
        }else{
            JOptionPane.showMessageDialog(this, "No se encontro ningun destino frecuente.");
        }
        
    }

    private void getDestinoSeleccionado() throws Exception {
        int index = destinosJList.getSelectedIndex();
        DestinoFrecuente destFrec = new DestinoFrecuente();
        if(index >= -1){
            destFrec = listaDestinos.get(index);
            this.posicionDestino = index;
            this.destinoSeleccionado = destFrec;
            this.llenarCamposByDestino(destFrec);        
        }else{
//            throw new Exception("Destino seleccionado no valido.");
        }
        
    }

    private void llenarCamposByDestino(DestinoFrecuente destino) {
        nombreDestinoTxt.setText(destino.getNombre());        
        Domicilio dom = destino.getDomicilio(); // Instancio el domicilio para mantener el codigo prolijo        
        calleTxt.setText(dom.getCalle());
        numeroTxt.setText(String.valueOf(dom.getNumero()));
        pisoTxt.setText(String.valueOf(dom.getPiso()));
        departamentoTxt.setText(dom.getDepartamento());
        codigoPostalTxt.setText(String.valueOf(dom.getCodigoPostal()));
        localidadTxt.setText(dom.getLocalidad());
        provinciaTxt.setText(dom.getProvincia());
    }

    private void guardarDestino() {
        DestinoFrecuente destino;
        if(isNuevo){
            destino = new DestinoFrecuente();
        }else{
            destino = listaDestinos.get(posicionDestino);
        }        
        
        //Seteo todos los datos de los campos en el destino a guardar
        destino.setNombre(nombreDestinoTxt.getText());
        
        Domicilio domDest = new Domicilio(); //domDest = domicilio del destino frecuente
        domDest.setCalle(calleTxt.getText());        
        
        if(numeroTxt.getText() != null && numeroTxt.getText().length() > 0){
            domDest.setNumero(Integer.valueOf(numeroTxt.getText())); // Estos IF son para evitar NullPointers
        }
        if(pisoTxt.getText() != null && pisoTxt.getText().length() > 0){
            domDest.setPiso(Integer.valueOf(pisoTxt.getText()));
        }
        
        domDest.setDepartamento(departamentoTxt.getText());
        
        if(codigoPostalTxt.getText() != null && codigoPostalTxt.getText().length() > 0){
            domDest.setCodigoPostal(Integer.valueOf(codigoPostalTxt.getText()));
        }
        
        domDest.setLocalidad(localidadTxt.getText());
        domDest.setProvincia(provinciaTxt.getText());
        destino.setDomicilio(domDest);
        
        try{
            DestinoFrecuenteBO destinoFrecuenteBO = new DestinoFrecuenteBO();
            if(isNuevo){
                destino = destinoFrecuenteBO.saveNewDestino(destino);
//                this.agregarDestinoEnLista(destino);
                this.actualizarLista();
                JOptionPane.showMessageDialog(this, "Destino agregado satisfactoriamente.");
            }else{
                destino = destinoFrecuenteBO.updateDestino(destino);
                this.actualizarLista();
            }
            this.limpiarCampos();
//            destinosJList.setEnabled(true);
        }catch(Exception ex){
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, ex);
        }
        
    }

    private void agregarDestinoEnLista(DestinoFrecuente destino) {
        DefaultListModel modelo = (DefaultListModel) destinosJList.getModel();
        modelo.addElement(destino.getNombre());
        destinosJList.setModel(modelo);
        listaDestinos.add(destino);
    }

    private void actualizarLista() {
        destinosJList.setModel(new DefaultListModel());
        this.getDestinosFrecuentes();
    }

    private void limpiarCampos() {
        nombreDestinoTxt.setText("");
        calleTxt.setText("");
        numeroTxt.setText("");
        pisoTxt.setText("");
        departamentoTxt.setText("");
        codigoPostalTxt.setText("");
        localidadTxt.setText("");
        provinciaTxt.setText("");
    }

    private void borrarSeleccionado() throws Exception {
        DefaultListModel modelo = (DefaultListModel) destinosJList.getModel();
        int index = destinosJList.getSelectedIndex();
        if(index < 0){
            throw new Exception("Debe seleccionar un destino!");
        }else{
            DestinoFrecuente destinoFrec = listaDestinos.get(index);
            DestinoFrecuenteBO destinoFrecuenteBO = new DestinoFrecuenteBO();
            destinoFrecuenteBO.deleteDestino(destinoFrec);
            this.actualizarLista();
        }
    }

}
